#include <iostream>
#include <string>
#include <cstring>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

//./client 服务器的IP 服务端的端口号
int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        std::cout<< argv[0] << "serve-ip serve-port" <<std::endl;
        exit(0);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    //1.创建socket
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    //判断一下是否创建成功，创建失败程序也就没有进行下去的必要，直接退出
    if(sockfd < 0)
    {
        std::cout<< "socket creat error" <<std::endl;
        exit(1);
    }

    //注意：客户端不需要显示的bind，但是一定要bind，
    //操作系统会自动的bind socket和自己的IP、随机生成的端口号
    //客户端是主动去连接服务端的，但不会有人主动去连接客户端的，所以客户端不需要listen()\accept()
    //服务端是等待客户端来连接，客户端是主动去连接服务端的
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    ::inet_pton(AF_INET, serverip.c_str(), &server.sin_addr);

    int n = ::connect(sockfd, (struct sockaddr *)&server, sizeof(server));
    if (n < 0)
    {
        std::cerr << "connect socket error" << std::endl;
        exit(2);
    }

    while(true)
    {
        std::string line;
        std::cout<< "Please Enter" <<std::endl;
        std::getline(std::cin, line);
        write(sockfd, line.c_str(), line.size());

        char echo_buffer[1024];
        ssize_t m = read(sockfd, echo_buffer, sizeof(echo_buffer));
        if(m > 0)
        {
            echo_buffer[m] = 0;
            std::cout << echo_buffer << std::endl;
        }
        //m==0服务端挂掉或者关闭，客户端直接结束
        //m<0说明读取错误,也直接结束
        else
        {
            break;
        }
    }
    close(sockfd);

    return 0;
}